using Sirenix.OdinInspector;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
namespace Custom.Daily.Toolkit
{
    public class FocusController : MonoBehaviour
    {
        [LabelText("允许聚焦的对象列表")]
        public List<GameObject> checkGameObjects;
        [LabelText("未聚焦到指定对象的回调")]
        public UnityEvent unityEvent;

        private Coroutine coroutine;
        private void OnEnable()
        {
            if(coroutine != null) StopCoroutine(coroutine);
            coroutine = StartCoroutine(CheckFocus());
        }
        private void OnDisable()
        {
            if(coroutine != null)
            {
                StopCoroutine(coroutine);
                coroutine = null;
            }
        }
        private void OnDestroy()
        {
            if (coroutine != null)
            {
                StopCoroutine(coroutine);
                coroutine = null;
            }
        }
        private IEnumerator CheckFocus()
        {
            while (true)
            {
                yield return new WaitForSeconds(0.1f);
                GameObject currentSelected = EventSystem.current.currentSelectedGameObject;
                bool isVal = false;
                if (currentSelected != null)
                {
                    foreach (var c in checkGameObjects)
                    {
                        if (c == currentSelected)
                        {
                            isVal = true;
                        }
                    }
                }
                if (!isVal)
                {
                    unityEvent?.Invoke();
                }
            }
        }
    }
}
